# --*-- coding:utf-8 --*--
import os

from src import request
from src import PrpCrypt
from src import Config as config
from src import Cookie
from src import DataDriver


class Login(object):
	DATA_PATH = os.path.join(config.project_dir, "Data")

	def login(self, loginKey=None, **kwargs):
		"""
		登录接口资源
		:param loginKey: 用户名
		:param kwargs: 关键字参数
		:return:
		"""
		if kwargs:
			data = eval(kwargs.get("data"))
			loginKey = data.get("loginKey")
			test_password = data.get("password") or config.test_password
			url = kwargs.get("url")
			data["password"] = test_password if any(
				i in url.split("/") for i in ("evssys", "erssys")) else PrpCrypt().encrypt(test_password)
			up_data = {
				"login_name": loginKey
			}
			kwargs["data"] = str(data)
			kwargs.update(up_data)
		else:
			url = config.login_url
			test_password = config.test_password
			kwargs = {
				"url": url,
				"method": "post",
				"content-type": "form-urlencoded",
				"login_name": str(loginKey),
				"data": str({
					'loginKey': str(loginKey),
					"username": str(loginKey),
					'password': test_password if any(
						i in url.split("/") for i in ("evssys", "erssys")) else PrpCrypt().encrypt(test_password),
					"language": "zh_CN"
				})
			}

		response = request(**kwargs)
		cookies = response.cookies.get_dict()
		authorization = "" if not response.json().get("Authorization") else str(response.json().get("Authorization"))
		# print(f"cookies: {cookies}", f"authorization: {authorization}", f"loginKey: {loginKey}", sep="\n", end="\n")
		Cookie().cookie_write(cookies, authorization, loginKey)
		return response.json()

	@DataDriver.run_data_from_excel(os.path.join(DATA_PATH, "LoginData.xlsx"))
	def login_1(self, login_name):
		try:
			self.login(login_name)
		except PermissionError as permission_error:
			raise PermissionError(f"{str(permission_error).split(': ')[-1]}文件已被打开，请先关闭后再运行，\n{permission_error}")


if __name__ == '__main__':
	# req_info = {
	# 	"method": "post",
	# 	"url": "/sys/auth/login",
	# 	"content-type": "form-urlencoded",
	# 	"data": """{
	# 		"loginKey": "zdh-002",
	# 		"password": "zfs123456",
	# 		"multiGroup": "true",
	# 		"loginPlatform": "PC",
	# 		"groupId": ""
	# 	}"""
	# }
	# Login().login(**req_info)
	Login().login_1()
